<template>
    <div class="w-full">
        <!-- 上传 -->
        <el-dialog v-model="state.uploadDialogVisible" width="80%" @close="state.uploadStutas = false">
            <div v-if="!state.uploadStutas">
                <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="state.headers" action="#"
                    :disabled="state.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                    :auto-upload="false" :before-upload="beforeUpload" drag>
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip text-center" slot="tip">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                    </div>
                </el-upload>
            </div>
            <div v-if="state.uploadStutas">
                <el-table ref="multipleTableRef" :data="paginatedData" style="width: 100%">
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="fullname" label="姓名" width="80" />
                    <el-table-column prop="sex" label="性别" align="center" width="60">
                        <template #default="scope">
                            <span>{{ scope.row.Sex === 0 ? '男' : '女' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="username" label="账号" width="120" align="center" />
                    <el-table-column prop="password" label="密码" width="120" align="center" />
                    <el-table-column prop="email" label="邮箱" width="180" />
                    <el-table-column prop="phonenumber" label="手机号" width="120" />
                    <el-table-column label="所属部门" align="center" width="100">
                        <template #default="scope">
                            {{ findDepartmentID(scope.row.departmentID) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="权限" align="center" width="100">
                        <template #default="scope">
                            <el-tag :type="findUserTypeName(scope.row.userTypeID) === 'root' ? 'info' : 'success'"
                                disable-transitions>{{ findUserTypeName(scope.row.userTypeID) }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="introduction" label="简介" />
                </el-table>
                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="state.parsePage.pageNum" :page-sizes="[5, 10]" :page-size="state.parsePage.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="state.parsePage.total" class="mt-6">
                </el-pagination>
            </div>
            <div slot="footer" class="mt-2 flex flex-row-reverse">
                <el-button @click="state.uploadDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitFileForm" class="me-2">
                    {{ state.uploadStutas ? '导 入' : '确 定' }}
                </el-button>
            </div>
        </el-dialog>
        <!-- 添加新增窗口 -->
        <el-dialog title="新增用户" v-model="state.addDialogVisible" width="50%">
            <el-form ref="registerForm" :model="state.registerForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="账号" prop="account">
                            <el-input v-model="state.registerForm.username"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="state.registerForm.password"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input type="password" v-model="state.registerForm.confirmPassword"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="state.registerForm.email"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phonenumber">
                            <el-input v-model="state.registerForm.phonenumber"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="fullname">
                            <el-input v-model="state.registerForm.fullname"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="state.registerForm.sex" placeholder="请选择">
                                <el-option label="男" :value="0"></el-option>
                                <el-option label="女" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="个人简介" prop="introduction">
                    <el-input type="textarea" v-model="state.registerForm.introduction" :rows="5" :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="submitForm">提交</el-button>
                        <el-button type="plain" @click="state.addDialogVisible = false">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 编辑用户弹出框 -->
        <el-dialog title="编辑用户" v-model="state.editDialogVisible" width="50%">
            <el-form ref="editForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="账号" prop="account">
                            <el-input v-model="state.editForm.username" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="state.editForm.email"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phonenumber">
                            <el-input v-model="state.editForm.phonenumber"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="fullname">
                            <el-input v-model="state.editForm.fullname"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex">
                            <el-select v-model="state.editForm.sex" placeholder="请选择">
                                <el-option label="男" :value="0"></el-option>
                                <el-option label="女" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="个人简介" prop="introduction">
                    <el-input type="textarea" v-model="state.editForm.introduction" :rows="5" :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow">提交</el-button>
                        <el-button type="plain" @click="state.editDialogVisible = false">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 分配权限窗口 -->
        <el-dialog title="分配权限" v-model="state.authorityDialogVisible" width="50%">
            <el-form ref="authority" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="账号" prop="account">
                            <el-input v-model="state.editForm.username" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="权限" prop="userTypeName">
                            <el-select v-model="state.editForm.userTypeID" placeholder="请选择">
                                <!-- 遍历state.userNames -->
                                <el-option v-for="(item, index ) in state.userTypeNameList" :key="index"
                                    :label="item.UserTypeName" :value="item.UserTypeID"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所属部门" prop="departmentID">
                            <el-select v-model="state.editForm.departmentID" placeholder="请选择">
                                <el-option v-for="item, index in state.departmentList" :key="index"
                                    :label="item.DepartmentName" :value="item.DepartmentID"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="flex justify-between">
                    <el-button type="primary" @click="updateRow">提交</el-button>
                    <el-button type="plain" @click="state.authorityDialogVisible = false">返回</el-button>
                </div>
            </el-form>
        </el-dialog>
        <el-row class="mb-1">
            <div class="w-full flex justify-end">
                <!-- <el-autocomplete v-model="state.stateData" @input="inputSearch" :fetch-suggestions="querySearchAsync"
                    placeholder="请输入关键字" @select="handleSelect" class="mr-2">
                    <template #suffix>
                        <el-icon color="#000">
                            <Search />
                        </el-icon>
                    </template>
                </el-autocomplete> -->
                <!-- <el-button type="info" :icon="User" @click="state.uploadDialogVisible = true">导入用户</el-button>
                <el-button type="warning" :icon="Download" @click="downloadUser('downLoad')">下载模板</el-button>
                <el-button type="success" :icon="Upload" @click="downloadUser()">导出excel表格</el-button>
                <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
                <el-button type="primary" :icon="Plus" @click="state.addDialogVisible = true">新增</el-button> -->
            </div>
        </el-row>
        <div class="overflow-hidden" :style="{
            'animation': state.drawerStatus ? 'openSearchKey 1s' : 'closeSearchKey 1s',
            'display': state.drawerStatus ? 'block' : 'none'
        }">
            <el-row class=" w-full p-2 flex">
                <el-col :span="18" class="flex items-center">
                    <el-autocomplete v-model="state.stateData" @input="inputSearch" :fetch-suggestions="querySearchAsync"
                        placeholder="请输入关键字" @select="handleSelect" class="mr-2">
                        <template #suffix>
                            <el-icon color="#000">
                                <Search />
                            </el-icon>
                        </template>
                    </el-autocomplete>
                    <el-button :icon="Search" type="primary" @click="getTableDate" class="ml-2">搜索</el-button>
                    <el-button :icon="Delete" type="danger" @click="state.searchKey = {}, getTableDate()">重置</el-button>
                </el-col>
                <el-col :span="4" class="flex items-center  ml-2">
                    <el-tooltip :disabled="disabled" content="导入工单数据" placement="bottom" effect="light">
                        <div @click="state.uploadDialogVisible = true"
                            class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Document />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <el-tooltip :disabled="disabled" content="下载工单模板" placement="bottom" effect="light">
                        <div @click="downloadUser('downLoad')"
                            class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Download />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <el-tooltip :disabled="disabled" content="新增工单数据" placement="bottom" effect="light">
                        <div @click="state.addDialogVisible = true" v-if="state.activeTab == 1"
                            class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Plus />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <el-tooltip :disabled="disabled" content="导出工单数据" placement="bottom" effect="light">
                        <div @click="downloadUser()" class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Upload />
                            </el-icon>
                        </div>
                    </el-tooltip>
                    <el-tooltip :disabled="disabled" content="批量删除" placement="bottom" effect="light">
                        <div @click="deleteAll" class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Delete />
                            </el-icon>
                        </div>
                    </el-tooltip>
                </el-col>
            </el-row>
        </div>

        <el-row class="flex justify-center mb-4">
            <div class="rounded-b-2xl w-14 flex justify-center flex-col items-center cursor-pointer"
                @click="state.drawerStatus = !state.drawerStatus">
                <el-icon :class="state.drawerStatus ? '-rotate-90' : 'rotate-90'">
                    <DArrowRight />
                </el-icon>
                <div class=" text-slate-400 text-xs">{{ state.drawerStatus ? '上拉隐藏' : '下拉搜索' }}</div>
            </div>
        </el-row>

        <el-table ref="multipleTableRef" :data="state.userListData" style="width: 100%"
            @selection-change="handleSelectionChange" id="my-table">
            <el-table-column type="selection" fixed="left" width="50" align="center" />
            <el-table-column prop="FullName" label="姓名" width="100" align="center" />
            <!-- 性别一栏 判断一下后台传过数据是1则为男，0为女-->
            <el-table-column prop="Sex" label="性别" width="80" align="center">
                <template #default="scope">
                    <span>{{ scope.row.Sex === 0 ? '男' : '女' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="头像" width="80" align="center">
                <template #default="scope">
                    <el-avatar :src="getAvatarUrl(scope.row.Avatar)"></el-avatar>
                </template>
            </el-table-column>
            <el-table-column prop="UserName" label="账号" width="120" align="center" />
            <el-table-column label="密码" width="120" align="center">
                <template #default="scope">
                    <el-row>
                        <el-col :span="16" class="flex justify-end items-center">
                            <span v-if="!scope.row.showPassword">*****</span>
                            <span v-else>{{ scope.row.Password }}</span>
                        </el-col>
                        <el-col :span="8" class="flex justify-start items-center">
                            <el-icon @mousedown="startTimer(scope.row)" @mouseup="clearTimer(scope.row)"
                                @mouseleave="clearTimer(scope.row)" class="ml-2 cursor-pointer"
                                v-if="!scope.row.showPassword">
                                <Hide />
                            </el-icon>
                            <el-icon @mousedown="startTimer(scope.row)" @mouseup="clearTimer(scope.row)"
                                @mouseleave="clearTimer(scope.row)" class="ml-2 cursor-pointer" v-else>
                                <ZoomIn />
                            </el-icon>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column prop="PhoneNumber" label="电话" width="120" align="center" />
            <el-table-column label="权限" width="120" align="center" :filters="[
                { text: 'Admin', value: 'Admin' },
                { text: 'root', value: 'root' },
            ]
                " :filter-method="filterTag" filter-placement="bottom-end">
                <template #default="scope">
                    <el-tag :type="scope.row.UserType.UserTypeName === 'root' ? 'info' : 'success'" disable-transitions>{{
                        scope.row.UserType.UserTypeName }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="Introduction" label="简介" width="120" align="center" />
            <el-table-column label="所属部门" width="120" align="center">
                <template #default="scope">{{ scope.row.Department.DepartmentName }}</template>
            </el-table-column>
            <el-table-column prop="Email" label="邮箱" width="180" align="center" />
            <el-table-column fixed="right" label="操作" min-width="250" align="center">
                <template #default="scope">
                    <el-button link type="warning" size="small" @click.prevent="openUpdata(scope.row)">
                        <el-icon>
                            <EditPen />
                        </el-icon>
                        编辑
                    </el-button>
                    <el-button link type="warning" size="small" @click.prevent="openAuthority(scope.row)">
                        <el-icon>
                            <Lock />
                        </el-icon>
                        分配权限
                    </el-button>
                    <el-button link type="danger" size="small" @click.prevent="deleteRow(scope.row.UserID)">
                        <el-icon>
                            <DeleteFilled />
                        </el-icon>
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination @size-change="handlehSizeChange" @current-change="handlehCurrentChange" :page-sizes="[5, 8, 10]"
            :page-size="state.pageSize" layout="total, jumper, prev, pager, next, sizes" :total="state.total" class="mt-2">
        </el-pagination>
    </div>
</template>

<script setup>
import { read, utils } from "xlsx";
// import Table2Excel from 'table-to-excel' // 引入  js-table2excel
import { getAvatarUrl } from '../utils/auth'
import { ElTable } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { userList, userListAll, userDelete, userUpdate, findAllName } from "../api/user"
import { findAllUserTypeName } from '../api/usertype'
import { register } from '../api/index'
import { findDepartmentAndID } from '../api/department/department'

import { downloadTemplateUser, downloadUserData, analysisExcel } from '../utils/tableMethod.js'

import { getToken } from '../utils/auth'
import { DeleteFilled, EditPen, Document, DArrowRight, Hide, ZoomIn, User, UploadFilled, Delete, Plus, Search, Lock, Upload, Download } from '@element-plus/icons-vue'
const registerForm = ref()
const editForm = ref()
const authority = ref()
import { useRouter } from 'vue-router'
const router = useRouter() //实例化
const value = ref(false)

import { messageCreate } from "../api/message/message";
import { useTabsStore } from '../store/store'
const useData = useTabsStore()

// 在验证规则中使用自定义校验函数
const validatePassword = (rule, value, callback) =>
{
    console.log(state.registerForm.password);
    if (value === '' || value === state.registerForm.password || value === state.editForm.password) {
        callback();
    } else {
        callback(new Error('两次输入密码不一致'));
    }
};
const state = reactive({
    userNames: [], //搜索关键词集合
    userListData: [],
    total: "",
    pageNum: 1,
    pageSize: 5,
    stateData: '',//搜索框提示词
    searchType: "exact",//搜索类型
    selectedIds: [],//选中的id
    authorityDialogVisible: false,
    drawerStatus: false,

    // 批量上传
    uploadDialogVisible: false,
    uploadStutas: false,
    // 是否禁用上传
    isUploading: false,
    // 解析后的表格数据
    parseTableData: [],
    parsePage: {
        total: "",
        pageNum: 1,
        pageSize: 5,
    },

    // 新增用户数据
    registerForm: {
        username: 'admin123456',
        password: '123',
        confirmPassword: '123',
        email: '2029481325@qq.com',
        phonenumber: '19815133485',
        fullname: '程封',
        sex: 1,
        introduction: '测试',
    },
    addDialogVisible: false, //新增用户窗口弹窗
    rules: {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        confirmPassword: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            { validator: validatePassword, trigger: 'blur' },
        ],
        email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
        ],
        phonenumber: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        fullname: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        sex: [
            { required: true, message: '请选择性别', trigger: 'change' },
        ],
        introduction: [
            { required: true, message: '请输入个人简介', trigger: 'blur' },
        ],
        userTypeName: [
            { required: true, message: '请选择权限', trigger: 'change' },
        ]
    },
    // 编辑用户数据
    editForm: {
        userId: '',
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        phonenumber: '',
        fullname: '',
        sex: '',
        introduction: '',
        userTypeName: '',
        UserTypeID: ''
    },
    // 权限分配
    userTypeNameList: [],

    // 部门列表
    departmentList: [],
    editDialogVisible: false,
})
const timer = ref(null);
const links = ref(null);
const startTimer = (row) =>
{
    timer.value = setTimeout(() =>
    {
        row.showPassword = true
        // 长按事件的处理逻辑
        console.log('长按事件触发');
    }, 800); // 按下 1 秒后触发长按事件
};
// 新增用户

const submitForm = () =>
{
    registerForm.value.validate((valid) =>
    {
        if (valid) {
            register(state.registerForm).then(res =>
            {
                ElMessage({
                    showClose: true,
                    message: '新增成功',
                    type: 'success',
                })
                state.addDialogVisible = false
                init()
            })
        } else {
            console.log('注册失败')
            return false
        }
    })
}
// 查找相应的权限
const findUserTypeName = (userTypeID) =>
{
    const index = state.userTypeNameList.findIndex(item => item.UserTypeID === userTypeID);
    if (index !== -1) {
        return state.userTypeNameList[index].UserTypeName;
    } else {
        return 'null';  // 或者你可以返回其他的一个默认值  
    }
}
// 查找相应的部门
const findDepartmentID = (departmentID) =>
{
    const index = state.departmentList.findIndex(item => item.DepartmentID === departmentID);
    if (index !== -1) {
        return state.departmentList[index].DepartmentName;
    } else {
        return 'null';  // 或者你可以返回其他的一个默认值
    }
}
// 打开分配权限窗口
const openAuthority = (row) =>
{
    state.editForm.userId = row.UserID
    state.editForm.username = row.UserName
    state.editForm.userTypeID = row.UserType.UserTypeID
    state.editForm.userTypeName = row.UserType.UserTypeName
    state.editForm.password = row.Password
    state.editForm.confirmPassword = row.Password
    state.editForm.email = row.Email
    state.editForm.phonenumber = row.PhoneNumber
    state.editForm.fullname = row.FullName
    state.editForm.sex = row.Sex
    state.editForm.introduction = row.Introduction
    state.editForm.departmentID = row.Department.DepartmentID
    state.authorityDialogVisible = true
}
// 编辑用户数据
const updateRow = () =>
{
    if (state.editForm.userTypeName != '') {
        userUpdate(state.editForm).then(res =>
        {
            ElMessage({
                showClose: true,
                message: '编辑成功',
                type: 'success',
            })
            state.editDialogVisible = false
            state.authorityDialogVisible = false
            init()
            messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 编辑列表数据`, operationType: 'add' })
        })
        console.log(state.editForm);
    } else {
        editForm.value.validate((valid) =>
        {
            if (valid) {
                userUpdate(state.editForm).then(res =>
                {
                    ElMessage({
                        showClose: true,
                        message: '分配成功',
                        type: 'success',
                    })
                    state.editDialogVisible = false
                    state.authorityDialogVisible = false
                    messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 给${state.editForm.username}分配ID为${state.editForm.UserTypeID}的权限`, operationType: 'add' })
                    init()
                }
                )
            } else {
                console.log('编辑失败')
                return false
            }
        })
    }
}
// 打开编辑窗口
const openUpdata = (row) =>
{
    state.editForm = {
        userId: row.UserID,
        username: row.UserName,
        password: row.Password,
        confirmPassword: row.Password,
        email: row.Email,
        phonenumber: row.PhoneNumber,
        fullname: row.FullName,
        sex: row.Sex,
        introduction: row.Introduction,
    }
    state.editDialogVisible = true
}
// 删除个人用户数据
const deleteRow = (userID) =>
{
    if (userID === 1) {
        // 当前用户不能删除自己的数据，弹出提示框
        ElMessage({
            showClose: true,
            message: '不能删除当前用户',
            type: 'warning',
        });
        return;
    }

    // 弹出确认删除的对话框
    ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () =>
        {
            // 用户点击确定，执行删除操作
            const res = await userDelete({ userId: userID });
            if (res.meta.status == 200) {
                // 如果删除操作失败
                ElMessage({
                    showClose: true,
                    message: '删除成功',
                    type: 'success',
                });
                messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 删除了 ID为${userID}的用户 数据`, operationType: 'download' })
            } else {
                ElMessage({
                    showClose: true,
                    message: '删除失败',
                    type: 'error',
                });
            }
            // 删除完成后执行初始化或其他操作
            init();
        })
        .catch(() =>
        {
            ElMessage('已取消');
            // 用户点击取消，不执行任何操作
        });
};
// 下载模板or下载数据表
const downloadUser = async (key) =>
{
    const tableHeader = [
        "序号",
        "姓名",
        "性别",
        "账号",
        "密码",
        "电话",
        "权限",
        "所属部门",
        "邮箱",
        "简介"
    ]
    const colsList = [ //设置表格的宽度
        {
            wpx: 50, //序号
        },
        {
            wpx: 100, //姓名
        },
        {
            wpx: 50, //性别
        },
        {
            wpx: 100, //密码
        },
        {
            wpx: 100, //电话
        },
        {
            wpx: 100, //权限
        },
        {
            wpx: 100, //所属部门
        },
        {
            wpx: 100,//邮箱
        },
        {
            wpx: 150, //简介
        }
    ];
    const positionObj = { start_r: 0, start_c: 0, end_r: 0, end_c: 8 }

    if (key == 'downLoad') {
        const instructions = [
            "导入说明.\n" +
            "1. 请不要改动Excel表结构并严格按照导入规则进行导入，否则将导入失败或出现不可预知的问题.\n" +
            "2. 请使用手机号码或者邮箱作为用户登录账号，用户的邮箱和手机号必须保证唯一性.\n" +
            "3. 登录密码默认为123456.\n" +
            "4. 所属部门名称必须与系统内已有的部门名称一致，否则将导致无法正常分配部门.\n" +
            "5. 所属权限名称必须与系统内已有的权限名称一致，否则将导致无法正常分配权限.\n" +
            "6. 请勿修改数据表结构，否则将导入失败的注明."
        ]
        const tableNameTemplate = "用户注册模板表"
        downloadTemplateUser(instructions, tableHeader, colsList, tableNameTemplate, positionObj)
        messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 下载了用户数据表模板`, operationType: 'download' })
    }
    else {
        let tabTable = []
        const tableName = "注册用户数据表"
        const res = await userListAll()
        const result = res.data.tableData
        for (let item of result) {
            // 获取用户类型名称  
            if (item.UserType) {
                item.UserType = item.UserType.UserTypeName;
            }

            // 获取部门名称  
            if (item.Department) {
                item.Department = item.Department.DepartmentName;
            }
        }

        // let dataRows = tableData.data.tableData.map((item) =>
        // {
        //     return [
        //         item.UserID,
        //         item.FullName,
        //         item.Sex,
        //         item.UserName,
        //         item.Password,
        //         item.PhoneNumber,
        //         item.UserType.UserTypeName,
        //         item.Department.DepartmentName,
        //         item.Email,
        //         item.Introduction
        //     ];
        // });
        for (let i = 0; i < result.length; i++) {
            const item = result[i];

            tabTable[i] = {
                UserID: item.UserID,
                FullName: item.FullName,
                Sex: item.Sex,
                UserName: item.UserName,
                Password: item.Password,
                PhoneNumber: item.PhoneNumber,
                UserType: item.UserType,
                Department: item.Department,
                Email: item.Email,
                Introduction: item.Introduction
            }
            console.log(item, "===>");
        }
        let dataRows = tabTable.map(obj => Object.values(obj))

        // let dataRows = tableData.data.tableData.map(obj => Object.values(obj));
        let titleRow = ['用户数据表'];
        downloadUserData(tableHeader, titleRow, dataRows, colsList, tableName, positionObj)
        // messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 下载了用户数据表`, operationType: 'download' })
    }
}

//上传文件之前的钩子
const beforeUpload = async (file) =>  
{
    const tableJson = await analysisExcel(file)
    state.uploadStutas = true
    console.log(tableJson.tableData, "========>");

    for (let index = 0; index < tableJson.tableData.length; index++) {
        const item = tableJson.tableData[index];
        state.parseTableData[index] = {
            id: item[0],
            fullname: item[1],
            sex: item[2],
            username: item[3],
            password: item[4],
            phonenumber: item[5],
            userTypeID: item[6],
            departmentID: item[7],
            email: item[8],
            introduction: item[9],
        }
    }
    state.parsePage.total = state.parseTableData.length
    console.log(state.parseTableData, "=====111===>");
}

const upload = ref()
// 提交上传文件
const submitFileForm = () =>
{
    console.log(state.userTypeNameList, "=======>");
    if (state.uploadStutas) {
        for (let index = 0; index < state.parseTableData.length; index++) {
            state.registerForm = state.parseTableData[index];
            register(state.registerForm).then(res =>
            {
                ElMessage({
                    showClose: true,
                    message: '新增成功',
                    type: 'success',
                })
                state.uploadStutas = false
                state.uploadDialogVisible = false
                init()
            })
        }
        messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 批量添加用户列表数据`, operationType: 'add' })
    } else {
        upload.value.submit();
    }
}

// 解析数据分页
// 分页
const handleSizeChange = (val) =>
{
    console.log(`每页 ${val} 条`)
    state.parsePage.pageSize = val
}
const handleCurrentChange = (val) =>
{
    console.log(`当前页: ${val}`);
    state.parsePage.pageNum = val;
}
// 计算分页数据
const paginatedData = computed(() =>
{
    const startIndex = (state.parsePage.pageNum - 1) * state.parsePage.pageSize;
    const endIndex = startIndex + state.parsePage.pageSize;
    return state.parseTableData.slice(startIndex, endIndex);
})



const clearTimer = (row) =>
{
    row.showPassword = false
    clearTimeout(timer.value);
};
// 筛选
const filterTag = (value, row) =>
{
    return row.UserType.UserTypeName === value
}
const init = async () =>
{
    const data = await userList({ pageSize: state.pageSize, pageNum: state.pageNum, username: state.stateData, searchType: state.searchType })
    state.userListData = data.data.userlist
    console.log(state.userListData, "++++++++");
    state.total = data.data.total
    state.pageSize = data.data.pageSize
    state.pageNum = data.data.pageNum
}
// 分页
const handlehSizeChange = (val) =>
{
    state.pageSize = val;
    state.pageNum = 1;
    init()
}
const handlehCurrentChange = (val) =>
{
    state.pageNum = Math.ceil(val);
    init()
}

//  搜索查找
const inputSearch = () =>
{
    state.searchType = 'fuzzy' //执行模糊搜索
    messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 搜索用户列表数据`, operationType: 'read' })
    init()
}
// 选择
const handleSelectionChange = (selection) =>
{
    state.selectedIds = selection.map(item => item.userID);
    console.log("选择的id", state.selectedIds);
}
// 批量删除
const deleteAll = () =>
{
    if (state.selectedIds.length === 0) {
        // 如果没有选择序号，显示提示
        ElMessage({
            showClose: true,
            message: '请选择序号',
            type: 'warning',
        })
    } else {
        // 弹出确认删除的对话框
        ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(async () =>
            {
                // 用户点击确定，执行删除操作
                let deleteStatus = true;

                for (const item of state.selectedIds) {
                    const res = await userDelete({ userId: item });
                    console.log(res);

                    // 如果删除操作失败
                    if (res.meta.status !== 200) {
                        deleteStatus = false;
                        break;  // 停止循环，不再继续删除剩余的项
                    }
                }

                // 根据删除操作的状态值显示相应的提示
                if (deleteStatus) {
                    ElMessage({
                        showClose: true,
                        message: '删除成功',
                        type: 'success',
                    });
                    messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().UserName}用户 批量删除了ID为${state.selectedIds}用户列表数据`, operationType: 'delete' })
                } else {
                    ElMessage({
                        showClose: true,
                        message: '删除失败',
                        type: 'error',
                    });
                }

                // 删除完成后执行初始化或其他操作
                init();
            })
            .catch(() =>
            {
                ElMessage('已取消')
                // 用户点击取消，不执行任何操作
            });
    }
};
// 搜索
let timeout
// 触发过滤条件
const querySearchAsync = (queryString, cb) =>
{
    const results = queryString
        ? state.userNames.filter(createFilter(queryString))
        : state.userNames

    clearTimeout(timeout)
    timeout = setTimeout(() =>
    {
        cb(results)
    }, 3000 * Math.random())
}
// 创建过滤
const createFilter = (queryString) =>
{
    return (restaurant) =>
    {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
// 获取所有的权限名
const getAllUserTypeName = async () =>
{
    const { data } = await findAllUserTypeName()
    state.userTypeNameList = data

}
// 搜索框选择
const handleSelect = (item) =>
{
    state.stateData = item.value
    init()
    console.log(state.stateData, "搜索词")
}
// 搜索框关键词
const getAllUserName = async () =>
{
    const { userNames } = await findAllName()
    state.userNames = userNames
    console.log(state.userNames, "搜索词")

    state.userNames = state.userNames.map(function (item)
    {
        return { value: item };
    });
}
// 获取部门全部名称
const getAllDepartmentNames = async () =>
{
    const { departmentAndID } = await findDepartmentAndID()
    state.departmentList = departmentAndID
    console.log(state.departmentList, "------------>");
}
onMounted(() =>
{
    init()
    getAllUserTypeName()
    getAllUserName()
    getAllDepartmentNames()
})
</script>

<style lang="scss" scoped>
:deep .el-table__row {
    height: 50px;
}

@keyframes openSearchKey {
    from {
        height: 0;
        display: none;
    }

    to {
        height: 48px;
        display: block;
    }
}

@keyframes closeSearchKey {
    from {
        height: 48px;
        display: block;
    }

    to {
        height: 0;
        display: none;
    }
}
</style>